const db=require('../db/index.js')
const getAddressList = (req, res) => {
  const { userId } = req.query;
  if (!userId) {
    return res.send({ status: 412, message: '请求参数不完整' });
  }

  db.query(
    'SELECT addressList FROM new_users WHERE id = ?',
    [userId],
    (err, results) => {
      if (err) {
        return res.send({ status: 500, message: '查询用户地址失败' });
      }

      if (results.length > 0) {
        let newAddressList = results[0].addressList;
        if(newAddressList  &&newAddressList.length > 0) {
          if (typeof newAddressList === 'string') {
            try {
             newAddressList = JSON.parse(newAddressList);
            } catch (e) {
              return res.send({ status: 500, message: '解析地址数据失败' });
            }
          }
         newAddressList =newAddressList.map(item => {
            if (typeof item === 'string') {
              try {
                return JSON.parse(item);  // 尝试将字符串解析为 JSON 对象
              } catch (e) {
                return item;  // 如果解析失败，返回原始字符串
              }
            }
            return item;  // 如果项本身不是字符串，直接返回原始项
          }
          );
          res.send({ status: 200, data:newAddressList });
        }else{
            res.send({ status: 404, message: '用户没有地址' });
        }
      } 
    }
  );
};
const addAddress = (req, res) => {
  const { mode, user, phone, local, detailLocal, userId } = req.body;
  // 检查参数是否完整
  if (!mode || !user || !phone || !local || !detailLocal || !userId) {
    return res.send({ status: 412, message: '请求参数不完整' });
  }

  // 查询用户的地址列表
  db.query('SELECT addressList FROM new_users WHERE id = ?', [userId], (err, results) => {
    if (err) {
      console.log(1);
      return res.send({ status: 500, message: '获取地址列表失败' });
    }

    // 处理查询结果，确保newAddressList 是一个数组
    let newAddressList = results[0]?.addressList ? (typeof results[0]?.addressList === 'string' ? JSON.parse(results[0]?.addressList) : results[0]?.addressList) : [];
    
    //如果电话号码重复，则不能添加
    for (let i = 0; i < newAddressList.length; i++) {
      if (newAddressList[i].phone === phone) {
        return res.send({ status: 400, message: '电话号码重复，不能添加' });
      }
    }

    
    if (newAddressList.length === 0) {
      // 地址列表为空，设置第一个地址为默认地址
     

      // 添加新的地址作为默认地址
      db.query(
        'UPDATE new_users set addressList = ? WHERE id = ?',
        [
          JSON.stringify([{
            mode,
            user,
            phone,
            local,
            detailLocal,
          }]),
          userId,
        ],
        (err, results) => {
          if (err) {
            console.log(2);
            return res.send({ status: 500, message: '添加默认地址失败' });
          }
          res.send({ status: 200, message: '默认地址添加成功' });
        }
      );
    } else {
      // 地址列表不为空
      if (mode === '默认') {
        // 更新原地址为非默认'，然后添加新的默认地址
        db.query(
          'SELECT addressList FROM new_users WHERE id = ?',
          [userId],
          (err, results) => {
            if (err) {
              console.log(3);
              return res.send({ status: 500, message: '获取地址失败' });
            }
        
            // 获取原始地址列表
            let newAddressList = results[0].addressList;
            newAddressList =newAddressList.map(item => {
              if (typeof item === 'string') {
                try {
                  return JSON.parse(item);  // 尝试将字符串解析为 JSON 对象
                } catch (e) {
                  return item;  // 如果解析失败，返回原始字符串
                }
              }
              return item;  // 如果项本身不是字符串，直接返回原始项
            }
          );

            // 查找 mode 为 "默认" 的地址项索引
            let defaultIndex = -1;
            for (let i = 0; i <newAddressList.length; i++) {
              if (newAddressList[i].mode === '默认') {
                defaultIndex = i;
                break;
              }
            }
        
            // 如果找到了 "默认" 地址项，则更新它
            if (defaultIndex !== -1) {
             newAddressList[defaultIndex].mode = '非默认';
            }
        
            // 更新原地址
            db.query(
              'UPDATE new_users set addressList = ? WHERE id = ?',
              [JSON.stringify(newAddressList), userId],
              (err, results) => {
                if (err) {
                  console.log(4);
                  return res.send({ status: 500, message: '更新原地址失败' });
                }
        
                // 添加新的地址
                db.query(
                  'UPDATE new_users set addressList = JSON_ARRAY_APPEND(addressList, "$", ?) WHERE id = ?',
                  [
                    JSON.stringify({
                      mode,
                      user,
                      phone,
                      local,
                      detailLocal,
                    }),
                    userId,
                  ],
                  (err, results) => {
                    if (err) {
                      console.log(5);
                      return res.send({ status: 500, message: '添加默认地址失败' });
                    }
                    
                    // 获取更新后的地址列表
                    db.query('SELECT addressList FROM new_users WHERE id = ?', [userId], (err, results) => {
                      if (err) {
                        console.log(6);
                        return res.send({ status: 500, message: '获取地址失败' });
                      }
                      res.send({ status: 200, message: '默认地址添加成功', data: results[0].addressList });
                    });
                  }
                );
              }
            );
          }
        );
      } else {
        // 非默认地址，直接添加到末尾
        db.query(
          'UPDATE new_users set addressList = JSON_ARRAY_APPEND(addressList, "$", ?) WHERE id = ?',
          [
            JSON.stringify({
              mode,
              user,
              phone,
              local,
              detailLocal,
            }),
            userId,
          ],
          (err, results) => {
            if (err) {
              console.log(7);
              return res.send({ status: 500, message: '添加地址失败' });
            }
            res.send({ status: 200, message: '地址添加成功' });
          }
        );
      }
    }
  });
};
const changeDefaultAddress = (req, res) => {
  const { userId, phone } = req.body;

  if(!userId || !phone) {
    return res.send({ status: 400, message: '缺少必要的参数' });
  }

  // 查询地址列表
  db.query('SELECT addressList FROM new_users WHERE id = ?', [userId], (err, results) => {
    if (err) {
      return res.send({ status: 500, message: '获取地址列表失败' });
    }

    // 解析地址列表，并将其转换为数组（如果已经是数组则直接使用）
    let newAddressList = results[0].addressList;
    newAddressList = newAddressList.map(item => {
      if (typeof item === 'string') {
        try {
          return JSON.parse(item);  // 尝试将字符串解析为 JSON 对象
        } catch (e) {
          return item;  // 如果解析失败，返回原始字符串
        }
      }
      return item;  // 如果项本身不是字符串，直接返回原始项
    });
    
    // 设置所有地址的 mode 为 '非默认'
    newAddressList = newAddressList.map(item => {
      item.mode = '非默认';
      return item;
    });

    // 找到对应 phone 的地址并设置其 mode 为 '默认'
    const targetAddress = newAddressList.find(item => item.phone === phone);
    if (targetAddress) {
      targetAddress.mode = '默认';
    } else {
      return res.send({ status: 404, message: '找不到该手机号对应的地址' });
    }

    // 更新数据库
    db.query('UPDATE new_users set addressList = ? WHERE id = ?', [JSON.stringify(newAddressList), userId], (err, results) => {
      if (err) {
        return res.send({ status: 500, message: '更新地址列表失败' });
      }
      res.send({ status: 200, message: '默认地址更新成功' });
    });
  });
};
const deleteAddress = (req, res) => {
  const { userId, phone } = req.body;
  if(!userId || !phone) {
    return res.send({ status: 400, message: '缺少必要的参数' });
  }
  db.query('SELECT addressList FROM new_users WHERE id = ?', [userId], (err, results) => {
    if (err) {
      return res.send({ status: 500, message: '获取地址列表失败' });
    }

    let newAddressList = results[0].addressList;
    newAddressList = newAddressList.map(item => {
      if (typeof item === 'string') {
        try {
          return JSON.parse(item);  // 尝试将字符串解析为 JSON 对象
        } catch (e) {
          return item;  // 如果解析失败，返回原始字符串
        }
      }
      return item;  // 如果项本身不是字符串，直接返回原始项
    });
    const index = newAddressList.findIndex(item => item.phone === phone);
    if (index === -1) {
      return res.send({ status: 404, message: '找不到该手机号对应的地址' });
    }
    if (newAddressList[index].mode === '默认') {
      return res.send({ status: 400, message: '默认地址不能删除' });
    }
    newAddressList.splice(index, 1);  // 从数组中删除找到的地址
    db.query('UPDATE new_users set addressList = ? WHERE id = ?', [JSON.stringify(newAddressList), userId], (err, results) => {
      if (err) {
        return res.send({ status: 500, message: '删除地址失败' });
      }
      res.send({ status: 200, message: '地址删除成功' });
    });
  })
}
const updateAddress = (req, res) => {
  const { userId, phone, mode, user, local, detailLocal } = req.body;

  if (!userId || !phone || !mode || !user || !local || !detailLocal) {
    return res.send({ status: 400, message: '缺少必要的参数' });
  }

  db.query('SELECT addressList FROM new_users WHERE id = ?', [userId], (err, results) => {
    if (err) {
      return res.send({ status: 500, message: '获取地址列表失败' });
    }
    let newAddressList = results[0].addressList;
    newAddressList = newAddressList.map(item => {
      if (typeof item === 'string') {
        try {
          return JSON.parse(item);  // 尝试将字符串解析为 JSON 对象
        } catch (e) {
          return item;  // 如果解析失败，返回原始字符串
        }
      }
      return item;  // 如果项本身不是字符串，直接返回原始项
    });
    const index = newAddressList.findIndex(item => item.phone === phone);
    if (index === -1) {
      return res.send({ status: 404, message: '找不到该手机号对应的地址' });
    }
    newAddressList[index].user = user;
    newAddressList[index].local = local;
    newAddressList[index].detailLocal = detailLocal;
    newAddressList[index].mode = mode;
    db.query('UPDATE new_users set addressList = ? WHERE id = ?', [JSON.stringify(newAddressList), userId], (err, results) => {
      if (err) {
        return res.send({ status: 500, message: '更新地址失败' });
      }
      res.send({ status: 200, message: '地址更新成功' });
    });
  })
    
}
module.exports={
    getAddressList,
    addAddress,
    changeDefaultAddress,
    deleteAddress,
    updateAddress
}